<template>
  <div class="create_rotary_page">
    <van-nav-bar title="创建转盘" left-arrow @click-left="() =>{this.$router.go(-1)}"/>
    <van-row class="rotary_table" type="flex" justify="center">
      <LuckyWheel
        ref="myLucky"
        width="250px"
        height="250px"
        :prizes="prizes"
        :blocks="blocks"
        :buttons="buttons"
        :defaultConfig="defaultConfig"
        @start="startCallback"
        @end="endCallback"
      />
    </van-row>
    <!--公告-->
    <van-row>
      <van-notice-bar
        left-icon="volume-o"
        text="支持创建2-8个奖项"
      />
    </van-row>
    <!--设置-->
    <van-row class="rotary_setting">
      <van-cell-group inset
                      class="setting_item"
                      v-for="(items, key) in prizes"
                      :key="key">
        <van-row>
          <van-col span="6" class="prize_image" @click="selectBox = key">
            <van-uploader :after-read="afterRead">
              <van-image
                width="2rem"
                height="2rem"
                cover
                :src="items.prizeImg"
              />
              <span class="setting_item_font">更换图片</span>
            </van-uploader>
          </van-col>
          <van-col span="18">
            <van-row>
              <van-field class="prize_input_setting" v-model="items.fonts[0].text" placeholder="一等奖">
                <template #right-icon>
                  <van-icon name="close" color="red" @click="deleteItem(key)"/>
                </template>
              </van-field>
              <van-field class="prize_input_setting" v-model="items.prizeName" placeholder="奖品名称"/>
            </van-row>
            <van-row>
              <van-cell value="奖品份数">
                <template #extra>
                  <van-stepper v-model="items.number"/>
                </template>
              </van-cell>
            </van-row>
          </van-col>
        </van-row>
      </van-cell-group>
    </van-row>
    <!--创建按钮-->
    <van-row>
      <van-col span="12" class="setting_item_button_box">
        <van-button :disabled="isDisabled"
                    plain
                    round
                    block
                    type="info"
                    @click="addBlackPrize"
                    color="#7232dd"
                    class="setting_item_button">
          创建空白项
        </van-button>
      </van-col>
      <van-col span="12" class="setting_item_button_box">
        <van-button :disabled="isDisabled"
                    plain
                    round
                    block
                    type="info"
                    @click="addPrize"
                    color="#7232dd"
                    class="setting_item_button">
          增加商品
        </van-button>
      </van-col>
    </van-row>
    <!--抽奖次数设置-->
    <van-row>
      <van-field required
                 v-model="lotteryNumber"
                 label="抽奖次数"
                 input-align="right"/>
    </van-row>
    <!--活动标题-->
    <van-row>
      <van-field required
                 v-model="activityTitle"
                 label="活动标题"
                 input-align="right"/>
    </van-row>
    <!--活动进行时间-->
    <van-row>
      <van-cell title="活动进行时间" :value="date" @click="show = true" is-link/>
      <van-calendar v-model="show" type="range" @confirm="onConfirm"/>
    </van-row>
    <!--抽奖概率-->
    <van-row>
      <van-collapse v-model="activeNames">
        <van-collapse-item title="中奖概率" name="defalut">
          <van-field v-for="(items, index) in prizes"
                     :key="index"
                     :label="items.fonts[0].text"
                     v-model="items.probability"
                     :placeholder="items.probability.toString()"
                     input-align="right"
                     type="digit"
                     :right-icon="percentageIcon"
          >
          </van-field>
        </van-collapse-item>
      </van-collapse>
    </van-row>
    <!--发起抽奖-->
    <van-row class="rotary_create_setting">
      <van-button round
                  block
                  type="info"
                  @click="createLuckyDraw"
                  color="#7232dd">
        发起抽奖
      </van-button>
    </van-row>
  </div>
</template>

<script>
import {
  Button,
  Cell,
  CellGroup,
  Col,
  Dialog,
  Field,
  Icon,
  Image as VanImage,
  NavBar,
  NoticeBar,
  Row,
  Stepper,
  Uploader,
  Collapse,
  CollapseItem,
  Calendar, Toast,
} from "vant";
import {LuckyWheel} from "@lucky-canvas/vue";
import {luckAdd} from "@/api/lucky";
import upload from "@/api/upload";

export default {
  name: "News",
  components: {
    LuckyWheel,
    [Row.name]: Row,
    [Col.name]: Col,
    [Icon.name]: Icon,
    [Button.name]: Button,
    [CellGroup.name]: CellGroup,
    [NavBar.name]: NavBar,
    [Cell.name]: Cell,
    [Field.name]: Field,
    [Stepper.name]: Stepper,
    [Uploader.name]: Uploader,
    [NoticeBar.name]: NoticeBar,
    [Dialog.name]: Dialog,
    [Collapse.name]: Collapse,
    [Calendar.name]: Calendar,
    [CollapseItem.name]: CollapseItem,
    VanImage
  },
  data: function () {
    return {
      blocks: [{
        padding: "30px",
        imgs: [{
          src: require('assets/img/转盘.png'),
          width: '100%',
          height: '100%',
          rotate: true
        }]
      }],
      buttons: [
        {
          radius: "50%",
          imgs: [{
            src: require('assets/img/按钮.png'),
            width: '100%',
            top: '-100%'
          }]
        }
      ],
      defaultConfig: {
        gutter: "1px"
      },
      prizes: [
        {
          background: "#937EF2",
          number: 1,
          prizeImg: "",
          prizeName: "华为Pro40",
          probability: 10,
          fonts: [{
            text: '一等奖',
            top: '50%',
            fontSize: "14px"
          }]
        },
        {
          background: "#F7DE8E",
          number: 1,
          prizeImg: "",
          prizeName: "小米电脑",
          probability: 20,
          fonts: [{
            text: '二等奖',
            top: '50%',
            fontSize: "14px"
          }]
        },
      ],

      lotteryNumber: 1,               // 抽奖次数
      activityTitle: "",
      isDisabled: false,              // 是否禁用按钮
      prizeBackgroundToggle: 2,       // 转换转盘背景颜色的
      percentageIcon: require("assets/img/百分号.png"),        // 百分号icon
      activeNames: ["defalut"],                        // 中奖概率设置的下拉框
      show: false,      // 活动时间设置的弹出框是否显示
      date: "",
      activityStartDate: "",      // 活动开始时间
      activityEndDate: "",         // 活动结束时间
      selectBox: 0,        // 当前选中的奖品设置框
    }
  },
  beforeUpdate() {
    this.isDisabled = this.prizes.length >= 8;
    if (this.activityEndDate !== "" && this.activityStartDate !== "") {
      this.date = `${this.activityStartDate} ~ ${this.activityEndDate}`
    }
  },
  methods: {
    afterRead(file) {
      this.$upload(file.file, "普通图片").then(res => {
        const {url} = res.data;
        this.prizes[this.selectBox].prizeImg = process.env.VUE_APP_IMG_URL + url;
      }).catch(err => {
        console.log(err);
      })
    },
    deleteItem(number) {
      if (this.prizes.length <= 2) {
        Dialog.confirm({
          title: "删除失败",
          message: "最少必须有两个奖项"
        })
        return
      }
      let tempArr = JSON.parse(JSON.stringify(this.prizes));
      tempArr.splice(parseInt(number), 1);
      this.prizes = tempArr
    },
    // 增加空白商品
    addBlackPrize() {
      let tempPrize = this.createDefalutSetting("谢谢参与", "谢谢参与", "http://192.168.201.104/%E6%9C%AA%E4%B8%AD%E5%A5%96-1639979379605.png", 9999);
      let tempArr = JSON.parse(JSON.stringify(this.prizes));
      tempArr.push(tempPrize);
      this.prizes = tempArr;
    },
    addPrize() {
      let tempPrize = this.createDefalutSetting();
      let tempArr = JSON.parse(JSON.stringify(this.prizes));
      tempArr.push(tempPrize);
      this.prizes = tempArr;
    },

    // 创建默认的商品添加的属性
    createDefalutSetting(prizeName = "", prizelevel = "", prizeImg = "", number=1) {
      let backgourndColor = ["#937EF2", "#F7DE8E", "#FFE300"];
      if (this.prizeBackgroundToggle > 2) {
        this.prizeBackgroundToggle = 0;
      }
      let background = backgourndColor[this.prizeBackgroundToggle];
      this.prizeBackgroundToggle += 1;
      return {
        background: background,
        number: number,
        prizeImg: prizeImg,
        prizeName: prizeName,
        probability: 0,
        fonts: [{
          text: prizelevel,
          top: '60%',
          fontSize: "14px"
        }],
      }
    },
    // 活动进行时间选择
    onConfirm(date) {
      const [start, end] = date;
      this.activityStartDate = this.formatDate(start);
      this.activityEndDate = this.formatDate(end);
      this.show = false;
    },
    // 时间格式化
    formatDate(date) {
      return `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()} 00:00:00`;
    },

    // 创建
    createLuckyDraw() {
      const rotaryTable = {
        count: this.lotteryNumber,
        startTime: this.activityStartDate,
        endTime: this.activityEndDate,
        title: this.activityTitle,
        prizes: this.prizes.map(item => ({...item, text: item.fonts[0].text, imgUrl: item.prizeImg}))
      }

      luckAdd(rotaryTable).then(res => {
        Dialog.alert({
          title: "创建成功",
          message: "创建成功，等待管理员审核"
        }).then(()=>{
          this.$router.replace("/main/personal");
        })
      }).catch(err => {
        if(err === "请先登录！"){
          Dialog.confirm({
            title: "请先登录",
            message: "请先登录"
          }).then(() => {
            this.$router.push({path: "/login", query: {redirect: this.$route.fullPath}});
          }).catch(() => {

          })
        }else{
          Toast.fail("创建失败");
        }
      })
    },
    startCallback() {
      // 调用抽奖组件的play方法开始游戏
      this.$refs.myLucky.play()
      // 模拟调用接口异步抽奖
      setTimeout(() => {
        // 假设后端返回的中奖索引是0
        const index = 0
        // 调用stop停止旋转并传递中奖索引
        this.$refs.myLucky.stop(index)
      }, 3000)
    },
    // 抽奖结束会触发end回调
    endCallback(prize) {
      console.log(prize)
    },
  }
}
</script>

<style scoped>
.create_rotary_page {
  background-color: rgb(242, 242, 242);
}

.rotary_table {
  padding: 10px;
  border-bottom: 2px solid rgb(242, 242, 242);
  background-color: #8EC5FC;
  background-image: linear-gradient(62deg, #8EC5FC 0%, #E0C3FC 100%);
}

.rotary_setting {
  padding-top: 1px;
}

.setting_item {
  margin-top: 10px;
}

.setting_item_button_box {
  padding: 20px 30px;
}

.setting_item_button {
  height: 30px;
  width: 125px;
  font-size: 14px;
}

.prize_image {
  padding: 8px;
  text-align: center;
  font-size: 14px;
}

.rotary_create_setting {
  padding: 10px;
}


.setting_item_font {
  color: rgb(115, 110, 255);
}

.prize_input_setting {
  height: 35px;
}
</style>
